import axios from 'axios'
import {ElMessage} from "element-plus";

const baseURL = '/api'

/**
 * @description axios初始化
 */
const request = axios.create({
    baseURL,
    timeout: 300000, // 超时时间
    headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        'clientid': 'e5cd7e4891bf95d1d19206ce24a7b32e',
        'connection': 'keep-alive',
        'istoken': 'true',
    },
})

/**
 * @description axios请求拦截器
 */
request.interceptors.request.use(requestConf, (error) => {
    return Promise.reject(error)
})

/**
 * @description axios响应拦截器
 */
request.interceptors.response.use(
    (response) => handleData(response),
    (error) => {
        ElMessage({ message: '网络故障请检查网络', type: 'error', duration: 5000 })
        const { response } = error
        if (response === undefined) {
            return {}
        } else return handleData(response)
    }
)

function requestConf(config) {
    // 确保固定的 Header 参数始终存在
    config.headers['clientid'] = 'e5cd7e4891bf95d1d19206ce24a7b32e'
    config.headers['connection'] = 'keep-alive'
    config.headers['istoken'] = 'true'
    
    // 请求头 token 处理 - SSR 环境下安全地获取 token
    const token = (typeof window !== 'undefined') ? localStorage.getItem('token') : null
    if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
}

// config, data, status, statusText
function handleData(res) {
    const { data, status } = res
    //console.log('data is', data)
    if (status !== 200) {
        ElMessage({
            message: `出错了：${res.statusText}`,
            type: 'error',
            duration: 5000,
        })
        return res
    }else{
        if (data && data.code !== 200) {
            if(data.code === 500){
                ElMessage({
                    message: `ERROR:：${data.msg}`,
                    type: 'error',
                    duration: 5000,
                })
            }else{
                if(data.code === 401){
                    const router = useRouter();
                    ElMessage({
                        message: data.msg||`登录已过期，请重新登录！`,
                        type: 'error',
                        duration: 5000,
                    })
                    router.push("/")
                    return res
                }
                ElMessage({
                    message: `错误：${data.msg}`,
                    type: 'error',
                    duration: 5000,
                })
            }
        }
        return data
    }
}

export default request
